import React, { Component, useRef, useState, useEffect } from "react";
import {
  Tabs,
  Row,
  Col,
  Typography,
  Form,
  Checkbox,
  Button,
  Input,
} from "antd";
import { reg } from "../../utils/validate";

import "./index.scss";
import { http } from "../../api";
import {
  UserOutlined,
  SafetyCertificateOutlined,
  LockOutlined,
  TabletOutlined,
} from "@ant-design/icons";
import { HashHistory } from "../../utils";
const { Title } = Typography;
const { TabPane } = Tabs;
const { phone, pwd } = reg;
export default function Login() {
  const callback = (key) => {
    console.log(key);
  };
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 3, span: 16 },
  };
  const tailLayoutme = {
    wrapperCol: { offset: 1, span: 16 },
  };
  const onFinish = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div className="login">
      <video
        src="https://img-baofun.zhhainiao.com/pcwallpaper_ugc/preview/3760b2031ff41ca0bd80bc7a8a13f7bb_preview.mp4"
        className="myvideo"
        id="myvideo"
        autoPlay
        loop
        playsInline
        muted
      ></video>
      <Row className="mylogin">
        <Col className="login-box" xs={23} sm={12} md={8} lg={8} xl={8} xxl={4}>
          <Title level={3} style={{ textAlign: "center", color: "#fff" }}>
            欢迎登陆
          </Title>
          <Tabs defaultActiveKey="1">
            <TabPane tab="密码登录" key="1">
              <Passlogin />
            </TabPane>
            <TabPane tab="验证码登录" key="2">
              <ShortLogin />
            </TabPane>
          </Tabs>
        </Col>
      </Row>
    </div>
  );
}
function Passlogin() {
  const passform = useRef();
  useEffect(() => {
    var thePhone = new URLSearchParams(HashHistory.location.search).get(
      "phone"
    ); //获取地址栏的参数
    if (thePhone) {
      passform.current.setFieldsValue({
        phone: thePhone,
      });
    }
  }, []);
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 3, span: 20 },
  };
  const tailLayoutme = {
    wrapperCol: { offset: 1, span: 16 },
  };
  const onFinish = (values) => {
    var body = {
      phone: values.phone,
      password: values.password,
    };
    http.login(body).then((res) => {
      if (res.data.code == 200) {
        if (values.remember) {
          localStorage.setItem("phone", values.phone);
          localStorage.setItem("password", values.password);
        }
        HashHistory.replace("/main");
        sessionStorage.setItem("token", res.data.token);
      }
    });
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div style={{ width: 400, height: 300 }}>
      <Form
        {...layout}
        name="pass_login"
        className="login-form"
        initialValues={{
          phone: localStorage.phone,
          password: localStorage.password,
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        ref={passform}
      >
        <Form.Item
          label="手机号码"
          name="phone"
          rules={[
            { required: true, message: "请输入手机号码" },
            {
              pattern: phone,
              message: "请输入正确的手机号码",
            },
          ]}
        >
          <Input
            placeholder="请输入手机号码"
            prefix={<TabletOutlined className="site-form-item-icon" />}
          />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            { required: true, message: "请输入登录密码" },
            {
              pattern: pwd,
              message: "请输入6-16位数字字母组合密码",
            },
          ]}
        >
          <Input.Password
            placeholder="请输入密码"
            prefix={<LockOutlined className="site-form-item-icon" />}
          />
        </Form.Item>

        <Form.Item
          {...tailLayout}
          name="remember"
          valuePropName="checked"
          className="marginmin"
        >
          <Checkbox>记住密码</Checkbox>
        </Form.Item>

        <Form.Item {...tailLayout} className="marginmin">
          <Button
            type="primary"
            htmlType="submit"
            block
            className="login-form-button"
          >
            登录
          </Button>
        </Form.Item>
        <Form.Item
          {...tailLayout}
          className="login-list"
          style={{ display: "flex", justifyContent: "space-between" }}
        >
          <span
            style={{ cursor: "pointer" }}
            onClick={() => HashHistory.push("/forgetpass")}
          >
            忘记密码
          </span>
          <span
            style={{ cursor: "pointer" }}
            onClick={() => HashHistory.push("/register")}
          >
            立即注册
          </span>
        </Form.Item>
      </Form>
    </div>
  );
}

function ShortLogin() {
  const smsForm = useRef();
  let [Flag, setFlag] = useState(true);
  let [count, setCount] = useState(60);
  let timer = null;
  useEffect(() => {
    var thePhone = new URLSearchParams(HashHistory.location.search).get(
      "phone"
    ); //获取地址栏的参数
    if (thePhone) {
      smsForm.current.setFieldsValue({
        phone: thePhone,
      });
    }
  }, []);
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 3, span: 18 },
  };
  const tailLayoutme = {
    wrapperCol: { offset: 1, span: 18 },
  };
  const onFinish = (values) => {
    console.log(values);
    http.checkcaptcha(values).then((res) => {
      if (res.data.code == 200) {
        HashHistory.replace("/main");
        sessionStorage.setItem("token", res.data.token);
        localStorage.setItem("phone", values.phone);
      }
    });
  };
  const startSend = () => {
    var phone = smsForm.current.getFieldsValue().phone;
    http.sentCaptcha({ phone: phone }).then((res) => {
      if (res.data.code == 200) {
        setFlag(false);
        timer = setInterval(() => {
          setCount(--count);
          if (count <= 0) {
            setFlag(true);
            clearInterval(timer);
          }
        }, 1000);
      }
    });
  };

  return (
    <div>
      <Form
        {...tailLayout}
        name="sms_login"
        className="login-form"
        initialValues={{
          phone: localStorage.phone,
          password: localStorage.password,
        }}
        onFinish={onFinish}
        ref={smsForm}
      >
        <Form.Item
          name="phone"
          rules={[
            { required: true, message: "请输入手机号码" },
            {
              pattern: phone,
              message: "请输入正确的手机号码",
            },
          ]}
        >
          <Input
            placeholder="请输入手机号码"
            prefix={<TabletOutlined className="site-form-item-icon" />}
          />
        </Form.Item>

        <Form.Item
          name="captcha"
          rules={[
            { required: true, message: "请输入验证码" },
            {
              pattern: /^\d{4}$/,
              message: "请输入四位数验证码",
            },
          ]}
        >
          <Row span={24}>
            <Col span={13}>
              <Input
                maxLength={4}
                prefix={
                  <SafetyCertificateOutlined className="site-form-item-icon" />
                }
                placeholder="请输入验证码"
              />
            </Col>
            <Col offset={1} span={10}>
              {Flag ? (
                <Button block type="primary" onClick={startSend}>
                  发送验证码
                </Button>
              ) : (
                <Button block type="info" disabled>
                  倒计时{count}s
                </Button>
              )}
            </Col>
          </Row>
        </Form.Item>

        <Form.Item>
          <Button
            type="danger"
            htmlType="submit"
            block
            className="login-form-button"
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
